package com.harry.resource.inner.entity;

import javax.persistence.*;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;

import com.harry.basis.BasePoEntity;
import static com.harry.configuration.ConstSettings.*;

import java.util.Set;

import lombok.Getter;
import lombok.Setter;

@Cacheable
@Getter
@Setter
@Entity
public class InnerArea extends BasePoEntity {

	private static final long serialVersionUID = 1L;

	@Column(length = SHORT_LENGTH)
	private String name;

	@Column(length = MINI_LENGTH)
	private String code;

	@Column(length = MEDIUM_LENGTH)
	private String codePath;

	@Fetch(FetchMode.JOIN)
	@ManyToOne(cascade = CascadeType.DETACH, fetch = FetchType.LAZY)
	@JoinColumn
	private InnerArea parent;

	@Fetch(FetchMode.JOIN)
	@OneToMany(cascade = CascadeType.DETACH, fetch = FetchType.LAZY)
	@JoinColumn
	private Set<InnerArea> children;

	// -----------------------------------
	public static void refreshCodePath(InnerArea area) {
		area.setCodePath(calcAreaCodePath(area));
	}

	private static String calcAreaCodePath(InnerArea area) {
		if (area.parent == null) {
			return "." + area.code + ".";
		} else {
			return "." + area.code + calcAreaCodePath(area.parent);
		}
	}
}
